package com.example.haoqisystem.Utils.WordUtils;

import com.example.haoqisystem.Annotation.WordAnnotation;
import org.apache.poi.xwpf.usermodel.*;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

public class ExportWord<T> {
    // 格式化日期
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 导出 Word 文档
     *
     * @param title   文档标题
     * @param dataset 数据集合
     * @param response HTTP 响应对象
     */
    public void exportWord(String title, Collection<T> dataset, HttpServletResponse response) {
        try {
            // 创建一个新的文档
            XWPFDocument document = new XWPFDocument();

            // 添加标题
            XWPFParagraph titleParagraph = document.createParagraph();
            titleParagraph.setAlignment(ParagraphAlignment.CENTER);
            XWPFRun titleRun = titleParagraph.createRun();
            titleRun.setText(title);
            titleRun.setBold(true);
            titleRun.setFontSize(16);

            // 创建表格
            XWPFTable table = document.createTable();

            // 添加表头
            T firstItem = dataset.stream().findFirst().orElse(null);
            if (firstItem != null) {
                List<String> headers = getExportFieldTitles(firstItem);
                XWPFTableRow headerRow = table.getRow(0);
                for (int i = 0; i < headers.size(); i++) {
                    XWPFTableCell cell = headerRow.getCell(i);
                    if (cell == null) {
                        cell = headerRow.createCell();
                    }
                    cell.setText(headers.get(i));
                    cell.setColor("C0C0C0");
                    cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
                    cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
                }
            }

            // 添加数据行
            for (T item : dataset) {
                XWPFTableRow dataRow = table.createRow();
                List<String> values = getExportFieldValues(item);
                for (int i = 0; i < values.size(); i++) {
                    XWPFTableCell cell = dataRow.getCell(i);
                    if (cell == null) {
                        cell = dataRow.createCell();
                    }
                    cell.setText(values.get(i));
                }
            }

            // 将文档写入输出流
            OutputStream out = response.getOutputStream();
            response.reset();
            response.setContentType("application/msword");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String((title + ".docx").getBytes(), StandardCharsets.UTF_8));
            document.write(out);
            out.flush();
            out.close();
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取导出字段的标题
     *
     * @param item 对象实例
     * @return 导出字段的标题列表
     */
    private List<String> getExportFieldTitles(T item) {
        List<String> exportFieldTitles = new ArrayList<>();
        Field[] fields = item.getClass().getDeclaredFields();
        for (Field field : fields) {
            WordAnnotation annotation = field.getAnnotation(WordAnnotation.class);
            if (annotation != null) {
                exportFieldTitles.add(annotation.exportName());
            }
        }
        return exportFieldTitles;
    }

    /**
     * 获取导出字段的值
     *
     * @param item 对象实例
     * @return 导出字段的值列表
     */
    private List<String> getExportFieldValues(T item) {
        List<String> exportFieldValues = new ArrayList<>();
        Field[] fields = item.getClass().getDeclaredFields();
        for (Field field : fields) {
            WordAnnotation annotation = field.getAnnotation(WordAnnotation.class);
            if (annotation != null) {
                String fieldName = field.getName();
                String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
                try {
                    Method getMethod = item.getClass().getMethod(getMethodName);
                    Object value = getMethod.invoke(item);
                    String textValue = getValue(value);
                    exportFieldValues.add(textValue);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return exportFieldValues;
    }

    /**
     * 获取字段的值
     *
     * @param value 字段值
     * @return 字段值的字符串表示
     */
    private String getValue(Object value) {
        String textValue = "";
        if (value == null) {
            return textValue;
        }
        if (value instanceof Date) {
            Date date = (Date) value;
            textValue = sdf.format(date);
        } else {
            textValue = value.toString();
        }
        return textValue;
    }
}
